﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;

namespace Lisphi.Lab.ProfWFChap02
{
    class Program
    {
        static void Main(string[] args)
        {
            using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                Console.Write("Select Workflow #1 or #2: ");
                string workflowNumber = Console.ReadLine();
                if (string.IsNullOrEmpty(workflowNumber)) return;
                string message = string.Empty;
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) 
                {
                    message = e.OutputParameters["Message"].ToString();
                    waitHandle.Set();
                };
                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                {
                    Console.WriteLine(e.Exception.Message);
                    waitHandle.Set();
                };

                Dictionary<string, object> inParams = new Dictionary<string, object>();

                WorkflowInstance instance = null;
                if (workflowNumber == "1")
                {
                    inParams.Add("FirstName", "Ben");
                    instance = workflowRuntime.CreateWorkflow(typeof(Workflow1), inParams);
                }
                else if (workflowNumber == "2")
                {
                    Console.Write("Input your Firstname: ");
                    string firstName = Console.ReadLine();
                    inParams.Add("FirstName", firstName);
                    instance = workflowRuntime.CreateWorkflow(typeof(Workflow2), inParams);
                }
                instance.Start();

                waitHandle.WaitOne();
                Console.WriteLine(message);
            }
            Console.WriteLine();
            Console.Write("Press any key to exit.");
            Console.Read();
        }
    }
}
